<?php
/**
 * Created by PhpStorm.
 * User: Kevin
 * Date: 2019/1/15
 * Time: 13:50
 */
namespace app\shop\controller;
use think\Controller;
use think\Db;
use think\Request;
class Login extends Controller
{
    /**
     * 登录页面
     * @return mixed
     */
    public function indexLogin(){
        if(request()->isAjax()){
            $account = trim(input('account'), ' ');
            $pwd = input('pwd');
            $yzm  = trim(input('yzm'));
            if($account == '') return json(['status' => 100, 'msg' => '请填写手机号或者邮箱']);
            if($pwd == '') return json(['status' => 100, 'msg' => '请填写密码']);
            if($yzm == '') return json(['status' => 100, 'msg' => '请填写图形验证码']);
            $where['user_email|user_phone'] = $account;
            $user = Db::table('up_u_user')->where($where)->find();
            if(empty($user)){
                return json(['status' => 100, 'msg' => '尚未注册,请先注册']);
            }
            if($user['user_role']!=2){
                return json(['status' => 100, 'msg' => '不属于企业端角色,不能登录']);
            }
            //查询图形验证码
            $yzm_data = Db::table('up_phonecode')->where('phone',$account)->find();
            if($yzm_data['yzm']!=$yzm || $yzm_data['yzm_status']==2){
                return json(['status' => 100, 'msg' => '请填写正确图形验证码']);
            }else{
                Db::table('up_phonecode')->where('phone',$account)->update(['yzm_status'=>2]);
            }
            $password = md5($pwd);
            if(!empty($user) && $password != $user['user_password']){
                return json(['status' => 100, 'msg' => '密码错误']);
            }
            if($user['user_status']!=1){
                return json(['status' => 100, 'msg' => '账号异常，请联系管理员']);
            }
            //手机号码是空的情况,跳转到手机绑定页面
            if($user['user_phone']==''){
                return json(['status' => 101, 'url' => url('shop/login/bind_Phone'), 'msg' => $user['user_id']]);
            }
            session('user_id',$user['user_id']);//商户id
            session('user_username',$user['user_username']);//商户名称
            session('user_image',$user['user_image']);//商户头像
            return json(['status' => 200, 'url' => url('shop/first/index'), 'msg' => '登录成功！']);
        }
        return $this->fetch('login/index_login');
    }
    //验证码
    public function pictureyzm(){
        $phone = input('phone');
        header("content-type:image/png");
        $validateLength=4;
        $strToDraw="";
        $chars=[
            "0","1","2","3","4",
            "5","6","7","8","9",
            "a","b","c","d","e","f","g",
            "h","i","j","k","l","m","n",
            "o","p","q","r","s","t",
            "u","v","w","x","y","z",
            "A","B","C","D","E","F","G",
            "H","I","J","K","L","M","N",
            "O","P","Q","R","S","T",
            "U","V","W","X","Y","Z"
        ];
        $imgW=80;
        $imgH=25;
        $imgRes=imagecreate($imgW,$imgH);
        $imgColor=imagecolorallocate($imgRes,255,255,100);
        $color=imagecolorallocate($imgRes,0,0,0);
        for($i=0;$i<$validateLength;$i++){
            $rand=rand(0,9);
            $strToDraw=$strToDraw.$chars[$rand];
        }
        imagestring($imgRes,5,20,5,$strToDraw,$color);
        for($i=0;$i<100;$i++){
            imagesetpixel($imgRes,rand(0,$imgW),rand(0,$imgH),$color);
        }
        if($phone){
            $where['phone'] = $phone;
            $res= Db::table('up_phonecode')->where($where)->find();
            if($res['id']!=''){ // 不等于空的时候
                $data['yzm'] = $strToDraw;
                $data['yzm_status'] = 1;

                Db::table('up_phonecode')->where($where)->update($data);
            }else{//等于空空
                $data['yzm'] = $strToDraw;
                $data['phone'] = $phone;
                Db::table('up_phonecode')->insert($data);
            }
        }

        imagepng($imgRes);
        imagedestroy($imgRes);exit;
    }
    /**
     * 发送验证码
     * @return \think\response\Json|void
     * phone       填写的手机号
     * type        发送场景   1 账号密码注册(绑定手机号码)   2 快捷登录
     * types       传1  图形验证
     * yzm         图形验证码
     *
     */
    public function getPhoneCode()
    {
        $params = input('');
        // 图形验证码
//        if(isset($params['types']) && $params['types'] == 1){
            $yzm  = input('yzm');
            $yzm_data = Db::table('up_phonecode')->where('phone',$params['phone'])->find();
            if($yzm_data['yzm'] != $yzm){
                return json(['status'=>100,'msg'=>'图形验证码错误']);
            }
            if($yzm_data['yzm_status'] != 1){
                return json(['status'=>100,'msg'=>'此图形验证码已使用，请重新获取']);
            }
            Db::table('up_phonecode')->where('phone',$params['phone'])->update(['yzm_status'=>2]);
//        }
        if(trim($params['phone'], ' ') == '') {
            return json(['status' => 100, 'msg' => '请输入手机号']);
        }
        $userInfo = Db::table('up_u_user')->where('user_phone', $params['phone'])->find();
        if(!empty($userInfo) && isset($params['type']) && $params['type'] == 1) { //注册
            return json(['status' => 100, 'msg' => '该手机号已注册']);
        }
        if(empty($userInfo) && isset($params['type']) && $params['type'] == 2) { //账号密码登录
            return json(['status' => 100, 'msg' => '该账号不存在']);
        }
        $code = GetRandCode();//6位数验证码
        $sendres = YzxSms($code, $params['phone'], '',562124);//发送验证码

        if($sendres['code'] != 0) {//发送不成功
            return json(['status' => 0, 'msg' => $sendres['msg']]);
        } else {
            $phone = $params['phone'];
            $isset = Db::table('up_phonecode')->where('phone', $phone)->find();
            $data = [
                'phone' => $params['phone'],//发送的手机号
                'code' => $code,//加密后的验证码
                'time' => time(),//验证码发送的时间戳
                'status' => 0,//验证码发送的时间戳
                'date_time' => date('Y-m-d H:i:s')
            ];
            if ($isset) {
                $res = Db::table('up_phonecode')->where('phone', $phone)->update($data);
            } else {
                $res = Db::table('up_phonecode')->insert($data);
            }
            if(!$res) {
                return json(['status' => 100, 'msg' => '数据库操作失败']);
            }
            return json(['status' => 200, 'msg' => md5($code)]);
        }
    }
    /**
     * 快捷登录
     * @return mixed|\think\response\Json
     */
    public function indexKuaijie(){
        if(request()->isAjax()){
            $phone = trim(input('phone'), ' ');
            $code = trim(input('code'), ' ');
            if($phone == ''){
                return json(['status' => 100, 'msg' => '请填写手机号']);
            }
            if($code == ''){
                return json(['status' => 100, 'msg' => '请填写验证码']);
            }

            $user = Db::table('up_u_user')->where('user_phone', $phone)->find();
            if(!empty($user)){
                if($user['user_status'] == 2 || $user['user_status'] == 3){
                    return json(['status' => 100, 'msg' => '账号异常，请联系管理员']);
                }
            }else{
                return json(['status' => 100, 'msg' => '该手机号尚未注册']);
            }
            if($user['user_role']!=2){
                return json(['status' => 100, 'msg' => '不属于企业端角色,不能登录']);
            }
            //=========验证验证码
            $yzm = Db::table('up_phonecode')
                ->where('phone', $phone)
                ->order('time desc')
                ->limit(1)
                ->find();
            if($code != $yzm['code']){
                return json(['status' => 100, 'msg' => '验证码错误']);
            }
            // 10分钟超时
            $now = time();
            if($now - $yzm['time'] >= 1801){
                return json(['status' => 100, 'msg' => '验证码超时']);
            }
            if($yzm['status'] == 1){
                return json(['status' => 100, 'msg' => '验证码失效']);
            }
            $res = Db::table('up_phonecode')->where('id', $yzm['id'])->setField('status', 1);
            if($res){
                session('user_id',$user['user_id']);//商户id
                session('user_username',$user['user_username']);//商户名称
                session('user_image',$user['user_image']);//商户头像
                return json(['status' => 200, 'url' => url('shop/first/index'), 'msg' => '登录成功！']);
            }
        }
        return $this->fetch('login/index_kuaijie');
    }

    /**
     * 手机注册
     * @return mixed|\think\response\Json
     */
    public function register(){
        if(request()->isAjax()){
            $phone = trim(input('phone'), ' ');
            $pwd = input('pwd');
            $oldpwd = input('oldpwd');
            $code  = trim(input('code'));
            $user_create = trim(input('user_create_id'), ' ');
            if($phone == '') return json(['status' => 100, 'msg' => '请填写手机号']);
            if($user_create == '') return json(['status' =>100, 'msg' => '请填写邀请码']);
            if($pwd == '') return json(['status' => 100, 'msg' => '请填写密码']);
            if($oldpwd == '') return json(['status' => 100, 'msg' => '请填写确认密码']);
            if($pwd!=$oldpwd)return json(['status' => 100, 'msg' => '2次密码不一致']);

            // 账号
            $exist = Db::table('up_u_user')->where('user_phone', $phone)->find();
            if(!empty($exist)){
                return json(['status' => 100, 'msg' => '该账号已注册']);
            }
            //查询加盟商的邀请码是否正确
            $where['user_role'] =  3;
            $where['user_create_id'] =  $user_create;
            $userInfo = Db::table('up_u_user')->where($where)->find();
            if($userInfo['user_id']==''){
                return json(['status' => 0, 'msg' => '您填写的邀请码不正确']);
            }
            // 验证码
            $yzm = Db::table('up_phonecode')
                ->where('phone', $phone)
                ->order('time desc')
                ->limit(1)
                ->find();
            if($code != $yzm['code']) return json(['status' => 0, 'msg' => '验证码错误']);
            if($yzm['code'] == 1) return json(['status' => 0, 'msg' => '验证码超时']);
            $token = $token = md5(date('YmdHis') . rand(100000, 999999));
            $insert = [
                'user_phone' => $phone,
                'user_time' => date('Y-m-d H:i:s'),
                'user_password' => md5($pwd),
                'user_token'=>$token,
                'user_last_time'=>date('Y-m-d H:i:s'),
                'f_user_id'=>$userInfo['user_id'],
                'user_pass'=>$pwd,
                'user_status'=>1,
                'user_role'=> 2,
            ];
            $res = Db::table('up_u_user')->insertGetId($insert);
            //插入企业和加盟商维护信息
            $dataList['union_jms_user_id'] = $userInfo['user_id'];
            $dataList['union_qy_user_id'] = $res;
            Db::table('up_invoice_union')->insertGetId($dataList);
            if($res){
                // 默认用户名    用户+ID
                Db::table('up_u_user')->where('user_id', $res)->setField('user_username', '用户' . $res);
                Db::table('up_phonecode')->where('id', $yzm['id'])->setField('status', 1);
                //查询这个用户
                $list = Db::table('up_u_user')->where('user_phone',$phone)->find();
                session('user_id',$list['user_id']);//商户id
                session('user_username',$list['user_username']);//商户名称
                session('user_image',$list['user_image']);//商户头像
                return json(['status' => 200, 'url' => url('shop/first/index'), 'msg' => '登录成功！']);
            }else{
                return json(['status' => 100, 'msg' => '注册失败']);
            }
        }
        return $this->fetch ('login/register');
    }
    /**
     * 邮箱注册
     * @return mixed|\think\response\Json
     */
    public function register1(){
        if(request()->isAjax()){
            $email = trim(input('email'), ' ');
            $pwd = input('pwd');
            $oldpwd = input('oldpwd');
            $user_create = trim(input('user_create_id'), ' ');
            if($email == '') return json(['status' => 100, 'msg' => '请填写邮箱']);
            if($user_create == '') return json(['status' =>100, 'msg' => '请填写邀请码']);
            if($pwd == '') return json(['status' => 100, 'msg' => '请填写密码']);
            if($oldpwd == '') return json(['status' => 100, 'msg' => '请填写确认密码']);
            if($pwd!=$oldpwd)return json(['status' => 100, 'msg' => '2次密码不一致']);
            // 账号
            $exist = Db::table('up_u_user')->where('user_email', $email)->find();
            if(!empty($exist)){
                return json(['status' => 100, 'msg' => '该账号已注册']);
            }
            //查询加盟商的邀请码是否正确
            $where['user_role'] =  3;
            $where['user_create_id'] =  $user_create;
            $userInfo = Db::table('up_u_user')->where($where)->find();
            if($userInfo['user_id']==''){
                return json(['status' => 0, 'msg' => '您填写的邀请码不正确']);
            }
            $token = $token = md5(date('YmdHis') . rand(100000, 999999));
            $insert = [
                'user_email' => $email,
                'user_time' => date('Y-m-d H:i:s'),
                'user_password' => md5($pwd),
                'user_token'=>$token,
                'user_last_time'=>date('Y-m-d H:i:s'),
                'f_user_id'=>$userInfo['user_id'],
                'user_pass'=>$pwd,
                'user_status'=>1,
                'user_role'=> 2,
            ];
            $res = Db::table('up_u_user')->insertGetId($insert);
            //插入企业和加盟商维护信息
            $dataList['union_jms_user_id'] = $userInfo['user_id'];
            $dataList['union_qy_user_id'] = $res;
            Db::table('up_invoice_union')->insertGetId($dataList);
            if($res){
                // 默认用户名    用户+ID
                Db::table('up_u_user')->where('user_id', $res)->setField('user_username', '用户' . $res);

                //查询这个用户
                $list = Db::table('up_u_user')->where('user_email',$email)->find();
                session('user_id',$list['user_id']);//商户id
                session('user_username',$list['user_username']);//商户名称
                session('user_image',$list['user_image']);//商户头像
                return json(['status' => 200, 'url' => url('shop/login/bind_Phone'), 'msg' => $res]);
            }else{
                return json(['status' => 100, 'msg' => '注册失败']);
            }
        }
        return $this->fetch ('login/register1');
    }
    //绑定手机号码
    public function bind_Phone(){
        if(request()->isAjax()){
            $phone = trim(input('phone'), ' ');
            $code = trim(input('code'), ' ');
            $user_id = trim(input('user_id'), ' ');
            if($phone == ''){
                return json(['status' => 100, 'msg' => '请填写手机号']);
            }
            if($code == ''){
                return json(['status' => 100, 'msg' => '请填写验证码']);
            }
            if($user_id == ''){
                return json(['status' => 100, 'msg' => '未读取到信息，请重新注册或者登陆绑定']);
            }

            $user = Db::table('up_u_user')->where('user_phone', $phone)->find();
            if(!empty($user)){
                return json(['status' => 100, 'msg' => '该手机号已经绑定,请填写新的手机号码']);
            }
            //=========验证验证码
            $yzm = Db::table('up_phonecode')
                ->where('phone', $phone)
                ->order('time desc')
                ->limit(1)
                ->find();
            if($code != $yzm['code']){
                return json(['status' => 100, 'msg' => '验证码错误']);
            }
            // 10分钟超时
            $now = time();
            if($now - $yzm['time'] >= 1801){
                return json(['status' => 100, 'msg' => '验证码超时']);
            }
            if($yzm['status'] == 1){
                return json(['status' => 100, 'msg' => '验证码失效']);
            }
            $res = Db::table('up_phonecode')->where('id', $yzm['id'])->setField('status', 1);
            if($res){
                 Db::table('up_u_user')->where('user_id',$user_id)->setField('user_phone',$phone);
                 $list = Db::table('up_u_user')->where('user_id',$user_id)->find();
                session('user_id',$list['user_id']);//商户id
                session('user_username',$list['user_username']);//商户名称
                session('user_image',$list['user_image']);//商户头像
                return json(['status' => 200, 'url' => url('shop/first/index'), 'msg' => '登录成功！']);
            }
        }
        $user_id = input('user_id');
        $this->assign('user_id',$user_id);
        return $this->fetch ('login/bind_phone');
    }

    /*
     * 退出登录
     */
    public function loginOut(){
        session(null);
        $this->redirect(url('shop/login/indexLogin'));
    }
}